<template>
  <div class="webchat_chat_info chat_info_box webchat_quick_reply_old">
    <el-tabs
            @tab-click="handleTabClick"
            class="quickreply_box">
      <!-- 自定义快捷回复 -->
      <el-tab-pane :label="$t('webchat.customize')" >
        <!-- 模糊搜索 -->
        <input-search
                class="search_box 111"
                :placeHolder="$t('webchat.searchQuickReply')"
                @quickSearch="selfQuickReplyInputSearch"
                :form="custSearchForm">
        </input-search>
        <!-- 自定义快捷回复列表 -->
        <el-row class="quickreply_cust_box">
          <!-- 分类列表 -->
          <div class="quickreplay_custom_con_box_old relative">
            <el-row class="tree">
              <el-col :span="10" style="border-right: 1px solid #ccc;height: 100%;overflow-y:auto">
                <div v-for="(model, index) in customQuickReply" :key="index" :index="index" @click.stop="custLiActive(model._id, index)" class="list_item" :class="currentCategoryId === model._id ? 'isActive' : ''">
                  {{model.name}}
                </div>
              </el-col>
              <el-col :span="14" v-if="selfQuickReplyObj[currentCategoryId] && selfQuickReplyObj[currentCategoryId].length !==0" style="height: 100%;overflow-y:auto">
                <div v-for="(item, index) in selfQuickReplyObj[currentCategoryId]" :key="item._id" class="right-item">
                  <div class="title">{{item.quickContent}}<div class="oper-btn"><span @click.stop="preview(item)">预览</span>
                    <span @click.stop="quickSendMsg(item, 'custom')">发送</span>
                    <span @click.stop="quickCopyMsg(item, 'custom')">使用</span>
                  </div>
                </div>
                  <div class="content" v-fold:curr='item' :style="{ '-webkit-line-clamp': item.num,'-webkit-box-orient': 'vertical'}"><span v-html="item.content"></span><span @click.stop="selfFold(item, index, 3)" class="main-color" v-if="item.isFold && item.num !== 3">收起</span>
                    <div v-if="item.isFold" class="fold-btn"><span @click.stop="selfFold(item, index, 9999)" v-if="item.num === 3">展开</span></div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <div class="quickreply_custome_btn clearfix">
              <el-button class="edit-btn" @click.stop="editCustSort" type="text" size="small">{{$t('webchat.editCustQuickReplay')}}</el-button>
            </div>
          </div>
          <div class="quickreply_public_none" v-show="customQuickReply.length === 0">
            {{$t('webchat.noData')}}
          </div>
        </el-row>
      </el-tab-pane>
      <!-- 公共快捷回复 -->
      <el-tab-pane :label="$t('webchat.systemCommon')">
        <!-- 模糊搜索 -->
        <input-search
                class="search_box"
                :placeHolder="$t('webchat.searchQuickReply')"
                @quickSearch="quickSearch"
                :form="publicSearchForm">
        </input-search>
        <!--公共快捷回复列表-->
        <el-row class="quickreply_public">
          <el-row class="tree" style="height:100%">
            <el-col :span="10" style="border-right: 1px solid #ccc;height: 100%;overflow-y:auto">
              <div v-for="(model, index) in sysQuickReply" :key="index" :index="index" @click.stop="quickSysLitoggle1(index, model._id)" class="list_item" :class="currCommonId === model._id ? 'isActive' : ''">
                {{model.name}}
                </div>
            </el-col>
            <el-col :span="14" v-if="commonQuickReplyObj[currCommonId] && commonQuickReplyObj[currCommonId].length !==0" style="height: 100%;overflow-y:auto">
              <div v-for="(item, index) in commonQuickReplyObj[currCommonId]" :key="index" class="right-item">
                <div class="title">{{item.quickContent}}<div class="oper-btn">
                  <span @click.stop="preview(item)">预览</span>
                  <span @click.stop="quickSendMsg(item, 'system')">发送</span>
                  <span @click.stop="quickCopyMsg(item, 'system')">使用</span>
                </div>
              </div>
                <div class="content" v-fold:curr='item' :style="{ '-webkit-line-clamp': item.num,'-webkit-box-orient': 'vertical'}"><span v-html="item.content"></span><span @click.stop="commonFold(item, index, 3)" class="main-color" v-if="item.isFold && item.num !== 3">收起</span>
                  <div v-if="item.isFold" class="fold-btn"><span @click.stop="commonFold(item, index, 9999)" v-if="item.num === 3">展开</span></div>
                </div>
              </div>
            </el-col>
          </el-row>
          <div class="quickreply_public_none" v-if="sysQuickReply.length === 0">
            {{$t('webchat.noData')}}
          </div>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <div class="privew km_baseinfo_preview" v-if="isShowKmPreview" :class="{ 'kmlayout' : isShowKmPreview, 'kmlayin': !isShowKmPreview}">
      <div class="km_preview_title">
        <span class="titleText">{{$t('km.preview')}}</span>
        <span @click.stop="quickSendMsg(currPreview, scopeTab)" class="useBtn">{{$t('sms.send')}}</span>
        <span @click.stop="quickCopyMsg(currPreview, scopeTab)" class="useBtn" style="right: 60px">{{$t('webchat.use')}}</span>
        <span class="el-icon-close" @click="closeKmPreview(currPreview.content)"></span>
      </div>
      <div style="margin: 20px">
        <p v-html="currPreview.quickContent" class="titleText contentTitle"></p>
        <div v-html="currPreview.content" class="editor-preview"></div>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
  import inputSearch from '@/components/public-modules/card/search/InputSearch'
  import bus from '@/store/eventBus'
  import { orderBy } from 'lodash'
  import { deepClone } from '@/utils/m7Utils'
  export default {
    name: 'WebchatQuickReplyOld',
    data () {
      return {
        currPreview: {},
        isShowKmPreview: false,
        commonQuickReplyObj: {},
        selfQuickReplyObj: {},
        publicSearchForm: {
          query: ''
        },
        custSearchForm: {
          query: ''
        },
        currCommonId: '',
        currentCategoryId: '',
        searchCustQuickReply: [],
        searchSysQuickReply: [],
        scopeTab: 'custom',
        sysFirstClick: false, // 是否第一次加载公共快捷回复
        dialogShow: false,
        sysQuickReply: [],
        customQuickReply: [],
        currentCustomReply: [],
        selfQuickReply: [],
        commonQuickReply: []
      }
    },
    directives: {
      fold: {
        // 指令的定义
        inserted: function (el, binding, vnode) {
          if (el && el.offsetHeight > 51) {
            binding.value.isFold = true
            binding.value.num = 3
          } else {
            binding.value.isFold = false
            binding.value.num = 'Infinity'
          }
        }
      }
    },
    methods: {
      commonFold (val, index, num) {
        val.num = num
        this.$set(this.commonQuickReplyObj[this.currCommonId], index, val)
      },
      selfFold (val, index, num) {
        val.num = num
        this.$set(this.selfQuickReplyObj[this.currentCategoryId], index, val)
      },
      closeKmPreview (val) { // 关闭预览弹窗
        this.isShowKmPreview = false
      },
      preview (val) { // 预览
        console.log(val)
        this.currPreview = val
        this.isShowKmPreview = true
      },
      changeFoldedStatus (event) { // 更改展开还是收起的状态
        let pane = event.currentTarget
        if (pane) {
          let flag = pane.getAttribute('ds_attr')
          let child = pane.previousSibling
          if (flag === 'unfolded') {
            child.style.display = 'block'
            pane.setAttribute('ds_attr', 'folded')
            pane.innerHTML = this.$t('email.folded')
          } else {
            child.style.display = '-webkit-box'
            pane.setAttribute('ds_attr', 'unfolded')
            pane.innerHTML = this.$t('email.unfolded')
          }
        }
      },
      trimFun (data) {
        let content = deepClone(data.content)
        let conNew = content.replace(/\s/g, '')
        if (conNew) {
          return true
        } else {
          return false
        }
      },
      quickSysLitoggle1 (index, model) {
        let self = this
        this.currCommonId = model || ''
        if (this.commonQuickReplyObj && this.commonQuickReplyObj[this.currCommonId]) {
          let data = this.commonQuickReplyObj[this.currCommonId]
          let arr = []
          for (let i = 0; i < data.length; i++) {
            let _obj = data[i]
            _obj.isFold = false
            _obj.num = 0
            arr.push(_obj)
          }
          this.$set(this.commonQuickReplyObj, this.currCommonId, arr)
          return false
        } else {
          let data = {
            tagParentId: model,
            moduleType: 'webchat'
          }
          self.$store.dispatch('newQueryQuickReply', data).then(res => {
            if (res && res.success) {
              const result = res.data || []
              let arr = []
              for (let i = 0; i < result.length; i++) {
                let _obj = result[i]
                _obj.isFold = false
                _obj.num = 0
                arr.push(_obj)
              }
              this.$set(this.commonQuickReplyObj, this.currCommonId, arr)
            }
          })
        }
      },
      custLiActive (item, index) {
        this.currentCategoryId = item || ''
        if (this.selfQuickReplyObj && this.selfQuickReplyObj[this.currentCategoryId]) {
          let data = this.selfQuickReplyObj[this.currentCategoryId]
          let arr = []
          for (let i = 0; i < data.length; i++) {
            let _obj = data[i]
            _obj.isFold = false
            _obj.num = 0
            arr.push(_obj)
          }
          this.$set(this.selfQuickReplyObj, this.currentCategoryId, arr)
          return false
        } else {
          this.$store.dispatch('newQueryAgentQuickReply', {'moduleType': 'webchat', 'tagParentId': this.currentCategoryId}).then((res) => {
            if (res && res.success) {
              console.log(res)
              let data = res.data || []
              let arr = []
              for (let i = 0; i < data.length; i++) {
                let _obj = data[i]
                _obj.isFold = false
                _obj.num = 0
                arr.push(_obj)
              }
              this.$set(this.selfQuickReplyObj, this.currentCategoryId, arr)
            }
          })
        }
      },
//      编辑分类
      editCustSort () {
        if (!this.$store.state.phoneBarShow) {
          bus.$emit('showCustQuickReply', {data: true})
        } else {
          bus.$emit('showEditCustomizeReply')
        }
      },
      // 发送快捷回复
      quickSendMsg (data, flag) {
        if (flag === 'custom') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-发送自定义回复'])
          this.$store.dispatch('addAgentQuickReplyNum', {_id: data._id})
        }
        if (flag === 'system') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-发送公共回复'])
          this.$store.dispatch('addCommonQuickReplyNum', {_id: data._id})
        }
        let obj = {
          type: 'text',
          con: data.content
        }
        bus.$emit('quickReplyHandleSubmit', obj)
      },
      // 复制快捷回复到输入框
      quickCopyMsg (data, flag) {
        if (flag === 'custom') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-粘贴自定义回复'])
          this.$store.dispatch('addAgentQuickReplyNum', {_id: data._id})
        }
        if (flag === 'system') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-粘贴公共回复'])
          this.$store.dispatch('addCommonQuickReplyNum', {_id: data._id})
        }
        let isOldLeaveMsg = this.webchatData.oldLeaveMsg ? true : false
        bus.$emit('quickReplyCopy', data.content, isOldLeaveMsg)
      },
      // 搜索快捷回复
      quickSearch (data) {
        let self = this
        let dataObj = {
          type: 'system',
          content: data,
          moduleType: 'webchat'
        }
        if (!data) {
          self.sysQuickReply = deepClone(self.commonQuickReply)
          if (self.sysQuickReply.length !== 0) {
            this.commonQuickReplyObj = {}
            self.quickSysLitoggle1(0, self.sysQuickReply[0]._id)
          }
          return
        }
        self.$store.dispatch('newSearchQuickReply', dataObj).then((res) => {
          if (res && res.success) {
            let _data = res.list || []
            self.sysQuickReply = []
            if (_data.length !== 0) {
              for (let i = 0; i < _data.length; i++) {
                const result = _data[i].childQuickReply || []
                let arr = []
                for (let i = 0; i < result.length; i++) {
                  let _obj = result[i]
                  _obj.isFold = false
                  _obj.num = 0
                  arr.push(_obj)
                }
                this.$set(this.commonQuickReplyObj, _data[i]._id, arr)
                if (_data[i].childQuickReply && _data[i].childQuickReply.length !== 0) {
                  delete _data[i].childQuickReply
                  self.sysQuickReply.push(_data[i])
                }
              }
              this.$nextTick(() => {
                self.quickSysLitoggle1(0, self.sysQuickReply[0]._id)
              })
            } else {
              this.currCommonId = ''
            }
          }
        })
      },
      // 自定义快捷回复搜索
      selfQuickReplyInputSearch (data) {
        let self = this
        let dataObj = {
          type: 'agent',
          content: data,
          moduleType: 'webchat'
        }
        if (!data) {
          self.customQuickReply = deepClone(self.selfQuickReply)
          if (self.customQuickReply.length !== 0) {
            self.selfQuickReplyObj = {}
            self.custLiActive(self.customQuickReply[0]._id, 0)
          }
          return
        }
        self.$store.dispatch('newSearchQuickReply', dataObj).then((res) => {
          if (res && res.success) {
            let _data = res.list || []
            self.customQuickReply = []
            if (_data.length !== 0) {
              for (let i = 0; i < _data.length; i++) {
                let data1 = _data[i].childQuickReply
                let arr = []
                for (let i = 0; i < data1.length; i++) {
                  let _obj = data1[i]
                  _obj.isFold = false
                  _obj.num = 0
                  arr.push(_obj)
                }
                this.$set(this.selfQuickReplyObj, _data[i]._id, arr)
                if (_data[i].childQuickReply && _data[i].childQuickReply.length !== 0) {
                  delete _data[i].childQuickReply
                  self.customQuickReply.push(_data[i])
                }
              }
              this.$nextTick(() => {
                self.custLiActive(self.customQuickReply[0]._id, 0)
              })
            } else {
              this.currentCategoryId = ''
            }
          }
        })
      },
      handleTabClick (tab) {
        let self = this
        if (tab.index === '1') {
          this.scopeTab = 'system'
          if (!this.sysFirstClick) {
            this.sysFirstClick = true
            this.$nextTick(() => {
              self.quickSysLitoggle1(0, self.sysQuickReply[0]._id)
            })
          }
          this.getAllCommonQuickReply()
        } else {
          this.scopeTab = 'custom'
        }
      },
      queueSort (data) {
        data = orderBy(data, [(o) => {
          let aa = o['sort'] || -1
          return aa
        }, (o) => {
          let aa = o['updatedTime'] || 0
          return aa
        }], ['asc', 'desc'])
        return data
      },
      // 获取自定义快捷回复
      getSelfQuickReply () {
        let self = this
        self.$store.dispatch('newQueryAgentQuickReplyTag', {'moduleType': 'webchat'}).then(res => {
          if (res && res.success) {
            let resData = deepClone(res.data)
            self.customQuickReply = self.queueSort(resData)
            self.selfQuickReply = this.queueSort(res.data)
            let currentIndex = 0
            if (self.customQuickReply.length) {
              if (!self.currentCategoryId) {
                self.currentCategoryId = self.customQuickReply[currentIndex]._id
              } else {
                self.customQuickReply.forEach((item, index) => {
                  if (item._id === self.currentCategoryId) {
                    currentIndex = index
                  }
                })
              }
            }
            this.$nextTick(() => {
              self.custLiActive(self.currentCategoryId, currentIndex)
            })
//            self.$store.dispatch('newQueryAgentQuickReply', {'moduleType': 'webchat', 'tagParentId': self.currentCategoryId}).then((res) => {
//              if (res && res.success) {
//                let resData = deepClone(res.data)
//                self.currentCustomReply = self.queueSort(resData)
//                if (self.customQuickReply.length) {
//                  let data = self.customQuickReply[currentIndex]
//                  if (!self.currentCategoryId) {
//                    data = self.customQuickReply[currentIndex]
//                    data.children = deepClone(res.data)
//                  }
//                  self.customQuickReply.splice(currentIndex, 1, data)
//                }
//              }
//            })
          }
        })
      },
      // 初始化获取所有的公共快捷回复
      getAllCommonQuickReply () {
        this.$store.dispatch('newQueryQuickReplyTag', {'moduleType': 'webchat'}).then((res) => {
          if (res && res.success) {
            this.sysQuickReply = this.queueSort(res.data) // 用于页面展示以及搜索数据
            this.commonQuickReply = this.queueSort(res.data) // 保留全部公共那个快捷回复的分类
          }
        })
      }
    },
    computed: {
      tabType () {
        let arr = this.$route.path.split('/')
        return arr[3]
      },
      sessionId () {
        let arr = this.$route.path.split('/')
        return arr[4]
      },
      webchatData () {
        //  会话的详细信息
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]) {
          return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_all.currentSession)
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_robot.currentSession)
        } else if (this.tabType === 'webchat_queue' && this.$store.state.webchat.current.webchat_queue.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_queue.currentSession)
        } else {
          return {}
        }
      }
    },
    components: {
      inputSearch
    },
    mounted () {
      bus.$on('refreshAgentReply', () => {
        this.currentCategoryId = ''
        this.selfQuickReplyObj = {}
        this.getSelfQuickReply()
        let data1 = {
          'moduleType': 'webchat'
        }
        this.$store.dispatch('getAllQuickReplyListNew', data1)
      })
    },
    beforeDestroy () {
      bus.$off('refreshAgentReply')
    },
    beforeMount () {
      let self = this
      this.getAllCommonQuickReply()
      self.getSelfQuickReply()
    }
  }
</script>
<style lang="stylus">
  @import "../../../assets/common.styl"
  .webchat_todo_conbox
    .basic_info
      .el-form
        padding 0
        margin-bottom 45px
      .el-col.el-col-24.full-add ,.el-col.el-col-24.full-del
        position absolute
        top -2px
        margin-left -6px
  .quickreplay_li
    .edit_del
      position absolute
      right 4px
      top 0
      padding 2px 0
  .vertical-align:after
    display inline-block
    width 0
    height 100%
    content "center"
    vertical-align middle
    overflow hidden
  .relative
    position relative
    .quickreply_custome_btn
      position absolute
      bottom 0
      left 0
      width 100%
      -webkit-box-sizing border-box
      box-sizing border-box
      background #fafafa
      -webkit-box-shadow 0px 0px 8px rgba(0,0,0,0.15)
      box-shadow 0px 0px 8px rgba(0,0,0,0.15)
      text-align center
      padding 10px 0
  .quickreplay_custom_con_box_old
    height calc(100vh - 174px)
    .tree
      height calc(100vh - 228px)
      // overflow-y auto
  .quickReSysIndex
    position relative
  .webchat_reply_tooltip
    word-break break-all
  .quick-re-con
    b
      font-weight normal
      padding-right 10px
      color #000
</style>
<style lang="stylus" scoped>
  @import "./style/webchatCon.styl"
  .webchat_quick_reply_old .quickreply_box .tree .right-item .title
    min-height 20px  
  .main-color
    color $c-main
    padding-left 10px
  .fold-btn
    position: absolute;
    right: 0px;
    top: 26px;
    color $c-main
    background-color: #fff;
    &:hover
      background-color #E5F1FF
  .right-item
    padding: 10px 16px;
    cursor pointer
    .title
      line-height: 16px;
      font-weight: bold;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      position relative
      .oper-btn
        visibility hidden
        background-color #E5F1FF
        color $c-main
        position: absolute;
        right: 0;
        top: 0px;
        span
          cursor pointer
          margin-right 10px
        span:last-child
          margin-right 0px
    &:hover
      background-color #E5F1FF
      .fold-btn
        background-color #E5F1FF
      .oper-btn
        visibility visible
    .content
      color #878787
      display: -webkit-box;
      box-orient: vertical;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 0;
      overflow: hidden;
      position relative
      word-break: break-all;
  .list_item
    cursor pointer
    padding-bottom 10px
    &:hover
      color $c-main
  .isActive
    color $c-main
  .kmlayout
    transition transform 0.35s
    box-shadow 0 3px 6px rgba(0, 0, 0, .3)
    animation kmMovelayout .4s
    @keyframes kmMovelayout
      0%
        transform  translateX(370px)
      100%
        transform  translateX(0)
  .kmlayin
    transform translateX(370px)
    transition transform 0.35s
  .km_baseinfo_preview
    position fixed
    z-index 1998
    right 0px
    top 95px
    bottom 100px
    background $cf-white
    border 1px solid #d3d3d3
    overflow-y auto
    overflow-x hidden
    cursor auto
    width 370px
    color $cf-level2
    .km_preview_title
      height: 38px;
      border-bottom: 1px solid #CCCCCC
      .titleText
        font-size 14px
        color #000000
        font-weight 600
        line-height: 38px
        margin-left: 20px
      .useBtn
        position: absolute
        right: 100px
        line-height: 38px
        cursor: pointer
      .useBtn:hover
        color #459ae9
    .el-icon-close
      position absolute
      width 14px
      font-size 14px
      line-height 38px
      cursor pointer
      z-index 2
      right 30px
      font-weight bold
    .contentTitle
      color: #000000
      font-weight: 400
      font-size: 14px
      margin-bottom: 10px
.noall
  -webkit-line-clamp: 3;
.quickreply_public_none
  padding 0 10px
  position absolute
  top 50%
  left 50px
</style>

